package com.jeesite.modules.flow.service;

import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.flow.dao.BizTodoItemDao;
import com.jeesite.modules.flow.entity.BizTodoItem;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.service.UserService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 待办事项Service业务层处理
 *
 * @author Xianlu Tech
 * @date 2019-11-08
 */
@Service
@Transactional
public class BizTodoItemService extends CrudService<BizTodoItemDao, BizTodoItem> {

    @Autowired
    private BizTodoItemDao bizTodoItemDao;

    @Autowired
    private UserService userService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private EmployeeService employeeService;


    /**
     * 获取单条数据
     * @param todoItem
     * @return
     */
    @Override
    public BizTodoItem get(BizTodoItem todoItem) {
        return super.get(todoItem);
    }

    /**
     * 查询分页数据
     * @param todoItem 查询条件
     * @return
     */
    @Override
    public Page<BizTodoItem> findPage(BizTodoItem todoItem) {
        return super.findPage(todoItem);
    }

    /**
     * 删除数据
     * @param todoItem
     */
    @Override
    @Transactional
    public void delete(BizTodoItem todoItem) {
        super.delete(todoItem);
    }

    @Transactional
    public int insertTodoItem(Map<String,Object> paramMap, String module) {
        BizTodoItem todoItem = new BizTodoItem();

        String instanceId = paramMap.get("instanceId").toString();
        String itemName = paramMap.get("itemName").toString();
        String itemContent = paramMap.get("itemContent").toString();
        String applyTime = paramMap.get("applyTime").toString();
        String applyUser = paramMap.get("applyUser").toString();
        String curUserOfficeCode = paramMap.get("officeCode").toString();

        String itemNameNew = applyUser + " " + applyTime + " 发起了 ";
        if("leave".equals(module)) {
            itemNameNew = itemNameNew + "请假流程：" + itemName;
        }
        todoItem.setItemName(itemNameNew);
        todoItem.setItemContent(itemContent);
        todoItem.setIsView("1");
        todoItem.setIsHandle("0");
        todoItem.setModule(module);
        todoItem.setTodoTime(new Date());
        List<Task> taskList = taskService.createTaskQuery().processInstanceId(instanceId).active().list();
        int counter = 0;
        for (Task task: taskList) {
            // todoitem 去重
            BizTodoItem bizTodoItem = bizTodoItemDao.selectTodoItemByTaskId(task.getId());
            if (bizTodoItem != null) continue;

            BizTodoItem newItem = new BizTodoItem();
            BeanUtils.copyProperties(todoItem, newItem);
            newItem.setInstanceId(instanceId);
            newItem.setTaskId(task.getId());
            newItem.setTaskName("task" + task.getTaskDefinitionKey().substring(0, 1).toUpperCase() + task.getTaskDefinitionKey().substring(1));
            newItem.setNodeName(task.getName());
            String assignee = task.getAssignee();
            if (StringUtils.isNotBlank(assignee)) {
                newItem.setTodoUserId(assignee);

                User userParam = new User();
                userParam.setUserCode(assignee);
                User user = userService.get(userParam);

                newItem.setTodoUserName(user.getUserName());
                super.save(newItem);
                counter++;
            } else {
                // 查询候选用户组
                List<String> todoUserIdList = bizTodoItemDao.selectTodoUserListByTaskId(task.getId());
                if (!CollectionUtils.isEmpty(todoUserIdList)) {
                    for (String todoUserId: todoUserIdList) {
                        boolean bSameDept = false;
                        // 如果任务id是已dept开头的，表明需要本部门的人员进行处理
                        if(task.getTaskDefinitionKey().indexOf("dept") == 0) {
                            // 查询当前需要处理的用户是否是申请人同一部门的用户
                            Employee em = new Employee();
                            Office off = new Office();
                            off.setOfficeCode(curUserOfficeCode);
                            em.setOffice(off);
                            em.setEmpCode(todoUserId);
                            List<Employee> employeeList = employeeService.findList(em);
                            if(!CollectionUtils.isEmpty(employeeList) && employeeList.size() > 0) {
                                bSameDept = true;
                            }
                        } else {
                            bSameDept = true;
                        }
                        if(bSameDept) {
                            User userParam = new User();
                            userParam.setUserCode(todoUserId);
                            User todoUser = userService.get(userParam);

                            newItem.setTodoUserId(todoUser.getUserCode());
                            newItem.setTodoUserName(todoUser.getUserName());
                            super.save(newItem);
                            counter++;
                        }
                    }
                } else {
                    // 查询候选用户
                    String todoUserId = bizTodoItemDao.selectTodoUserByTaskId(task.getId());

                    User userParam = new User();
                    userParam.setUserCode(todoUserId);
                    User todoUser = userService.get(userParam);

                    newItem.setTodoUserId(todoUser.getUserCode());
                    newItem.setTodoUserName(todoUser.getUserName());
                    super.save(newItem);
                    counter++;
                }
            }
        }
        return counter;
    }

    public BizTodoItem selectBizTodoItemByCondition(String taskId, String todoUserId) {
        return bizTodoItemDao.selectTodoItemByCondition(taskId, todoUserId);
    }

    public BizTodoItem selectTodoItemByInstanceId(String instanceId) {
        return bizTodoItemDao.selectTodoItemByInstanceId(instanceId);
    }
}
